package zl.controller;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import zl.bean.RespBean;
import zl.bean.User;
import zl.service.UserService;

import java.sql.SQLException;

@Controller
@RequestMapping("/api/user")
public class UserController  {
    @Autowired
    private UserService userService;


    @GetMapping("/page")
    @ResponseBody
    public RespBean selectAllUser(Integer currentPage , String keyword) throws SQLException {
        PageInfo<User> page = userService.selectByPage(currentPage, keyword);
        return RespBean.ok("查询成功",page);
    }

    @ResponseBody
    @PostMapping("/add")
    public RespBean addUser(@RequestBody User user){
        if(StrUtil.hasBlank(user.getUsername()) || StrUtil.hasBlank(user.getPassword()) ||
                StrUtil.hasBlank(user.getNickname()) || StrUtil.hasBlank(user.getRole())){
            return RespBean.error("账号，用户名,密码，身份不能为空");
        }
        int i =userService.addUser(user);
        if(i==1){
            return RespBean.ok("添加成功");
        }else {
            return RespBean.error("账号重复，请重新填写");
        }

    }

    @GetMapping("/{id}")
    @ResponseBody
    public RespBean selectById(@PathVariable Integer id){
        User user = userService.selectById(id);
        return RespBean.ok("查询成功",user);
    }

    @PostMapping("/update")
    @ResponseBody
    public RespBean updateUser(@RequestBody User user){
        System.out.println(user.toString());
        if(StrUtil.hasBlank(user.getNickname()) || StrUtil.hasBlank(user.getRole())){
            return RespBean.error("用户名,身份不能为空");
        }
        int i =userService.updateUser(user);
        if(i==1){
            return RespBean.ok("修改成功");
        }else{
            return RespBean.error("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public RespBean deleteUser(@PathVariable Integer id) throws SQLException {
        int i =userService.deleteUser(id);
        if(i==1){
            return RespBean.ok("删除成功");
        }else{
            return RespBean.error("该用户下有小说,删除失败");
        }
    }



}
